package rxjava.application.com.androidmyp.Presenter;

import android.util.Log;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.OnResponseListener;
import com.yolanda.nohttp.Request;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.RequestQueue;
import com.yolanda.nohttp.Response;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit.Call;
import retrofit.Callback;
import retrofit.Retrofit;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;
import rxjava.application.com.androidmyp.Beans.BaseBean;
import rxjava.application.com.androidmyp.Beans.SchoolClass;
import rxjava.application.com.androidmyp.Beans.User;
import rxjava.application.com.androidmyp.BuildConfig;
import rxjava.application.com.androidmyp.Data.ApiException;
import rxjava.application.com.androidmyp.Data.ApiInterceptor;
import rxjava.application.com.androidmyp.Data.ApiManger;
import rxjava.application.com.androidmyp.Data.RxSchedulers;
import rxjava.application.com.androidmyp.Login.UserLoginContract;

/**
 * Created by Administrator on 2016/4/13.
 */
public class LoginPresenter implements BasePresenter{
    private UserLoginContract mView;//当前的页面
    private CompositeSubscription msubscription;//管理所有的订阅

    public LoginPresenter(UserLoginContract mView) {
        this.mView = mView;
        this.mView.setPresenter(this);
        this.msubscription = new CompositeSubscription();

    }

    /**
     * 用户登录
     * 使用noHttp进行网络请求
     */
    public void login(String userName, String password) {
        String url = "http://172.16.1.174/instalment1.4/";
        final int NOHTTP_WHAT_TEST = 0x001;
        if (userName.isEmpty()) {
            mView.showToast("用户名不能为空");
            return;
        } else if (password.isEmpty()) {
            mView.showToast("密码不能为空");
            return;
        }
        RequestQueue requestQueue = NoHttp.newRequestQueue();
        // 创建请求对象
        final Request<String> request = NoHttp.createStringRequest(url, RequestMethod.POST);
        // 添加请求参数
        request.add("username", userName);
        request.add("password", password);
        requestQueue.add(NOHTTP_WHAT_TEST, request, new OnResponseListener<String>() {
            @Override
            public void onStart(int what) {
            }

            @Override
            public void onSucceed(int what, Response<String> response) {
                if (BuildConfig.DEBUG) Log.d("LoginPresenter", response.get().toString());
                mView.loginSuccess();
            }

            @Override
            public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) {
                mView.loginFailed();
            }

            @Override
            public void onFinish(int what) {
            }
        });

    }

    /**
     * 用户登录
     * 使用rx+retrofit进行网络请求
     * @param userName
     * @param passWord
     */
    public void loginWithRx(String userName, String passWord) {
        if (userName.isEmpty()) {
            mView.showToast("用户名不能为空");
            return;
        } else if (passWord.isEmpty()) {
            mView.showToast("密码不能为空");
            return;
        }
        msubscription.add(ApiManger.getIntance().api.UserLogin(userName, passWord)
                .flatMap(new Func1<BaseBean<User>, Observable<User>>() {
                    @Override
                    public Observable<User> call(BaseBean<User> userTempBaseBean) {
                        return new ApiInterceptor().flatResult(userTempBaseBean);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<User>() {
                    @Override
                    public void onCompleted() {
                        mView.loginSuccess();
                    }

                    @Override
                    public void onError(Throwable e) {
                        ApiException es = (ApiException) e;
                        mView.loginFailed();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(User s) {
                        mView.showToast(s.toString());
                    }
                }));
    }

    /**
     * 单独使用retrofit请求网络
     * @param name
     * @param ps
     * 返回类型为Gson包下的JsonObejct
     */
    public void loginWithRetrofit(String name, String ps) {
        Call<JsonObject> json = ApiManger.getIntance().api.UserLoginWithRetrofit(name, ps);
        json.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(retrofit.Response<JsonObject> response, Retrofit retrofit) {
                JsonObject jsonObject = response.body();
                for (Map.Entry<String, JsonElement> element : jsonObject.entrySet()) {
                    Log.d("LoginPresenter", element.getKey());
                }
                mView.showToast(response.body().toString());
            }

            @Override
            public void onFailure(Throwable t) {
                mView.loginFailed();
                t.printStackTrace();
            }
        });
    }


    /**
     * 获取class
     */
    public void getClassInfo() {
        HashMap<String, String> map = new HashMap<>();
        map.put("id", "3");
        Subscription i  = ApiManger.getIntance().api.getClass(map)
                .flatMap(new Func1<BaseBean<List<SchoolClass>>, Observable<List<SchoolClass>>>() {
                    @Override
                    public Observable<List<SchoolClass>> call(BaseBean<List<SchoolClass>> listBaseBean) {
                        return new ApiInterceptor().flatResult(listBaseBean);
                    }
                })
                .compose(RxSchedulers.<List<SchoolClass>>IO_Main())
                .subscribe(new Subscriber<List<SchoolClass>>() {
                    @Override
                    public void onCompleted() {
                        //获取数据完成
                        mView.loginSuccess();
                    }

                    @Override
                    public void onError(Throwable e) {
                       ApiException apiException = (ApiException) e;
                        mView.showToast(apiException.getRespMSg());
                    }

                    @Override
                    public void onNext(List<SchoolClass> schoolClasses) {
                        //得到数据，在页面可以进行数据绑定操作
                    }
                });
        this.msubscription.add(i);//把订阅加入管理集合中
    }

    @Override
    public void onDestroy() {
        //在activity结束生命周期的时候取消订阅，解除对context的引用
        if(msubscription != null){
            this.msubscription.unsubscribe();
        }
    }
}
